<script lang="ts" setup>
    import { ref, reactive, computed, watch, onMounted, provide } from 'vue';
    import IndexTreeHeader from '../components/IndexTreeHeader/index.vue'
    import GraphContent from './graphContent/index.vue'
    import IndexConfig from './indexConfig/index.vue'
    import API from '@/services';
    import Bus from '@/utils/emmit'
    import { useRouter, useRoute} from 'vue-router';
    import * as RouteNames from '@/router/consts';
    import { Message } from '@arco-design/web-vue';
    import _ from 'lodash';
    import {NumberUnit, defaultConfig} from '@/constants/indexTree'
    import { useStore } from '@/store';
    import {getDateOfWeek, showQuerterFormatter} from '@/utils/util';
    const store = useStore();
    const route = useRoute();
    const router = useRouter();
    const id = ref<any>(route.query.id)
    const isNotMicroApp = ref<boolean>(true);
    isNotMicroApp.value = !window.__MICRO_APP_ENVIRONMENT__;
    if (isNotMicroApp.value) {
        document.getElementsByTagName('body')[0].className = 'metrics-not-micro-app';
    }

    // const str = ref('指标名称')
    const historyName = computed(() => store.state.indextree.metricsTreeName);
    const metricsDescript = computed(() => store.state.indextree.metricsDescript);
    const metricsName = ref<string>('')
    const sortTreeOption = ref<any>()
    const isEditStatus = ref<boolean>(false)
    provide('sortTreeOption', sortTreeOption)
    const curMetricsItem = ref()
    const addDesciptValue = ref() // 添加描述
    const addMetricsCardRef = ref()

    const metricsConfigObj = reactive({
        value: {
            ...defaultConfig
        }
        
    })
    const graphContent = ref()
    let metricsLeftConfig = reactive<any>({
        MetricsTreeCard: {}
    })
    let cards = reactive<any>({})
    const popupVisible = ref<boolean>(false)
    const treeEditId = ref<any>()

    const setCardData = ref<any> ()
    const manyCardList = ref<any>() //用于保持时指标卡集合

    const firstMetricsData = ref<any>() // 创建的第一个指标卡
    // 选择树指标
    const {
      metricsGroup: { getMetricsGroupListRoot }
    } = API;
     /* 分类节点列表 */
    const getClassfiyList = async () => {
        
      try {
        let { code, data } = await getMetricsGroupListRoot({
          display: 1,
          pageNum: 1,
          pageSize: 50
        });
        if (code === 200 && Array.isArray(data?.list)) {
          sortTreeOption.value = data?.list;
        }
      } catch (error) {
        console.log(error);
      }
    };
    const timer = ref<any>()
    const initCardParam = ref<any>()

    // 点击指标卡更新配置项
    Bus.on('clickMetricsConfig', (val:any)=> {
        const cloneVal = _.cloneDeep(val)
        const dateCondition = cloneVal.dateCondition
        const compareTimerConfig = cloneVal.compare.dateCondition
        // 默认数据时间的配置
        if ( dateCondition.dateMode === 'FIXDATE') {
            if (dateCondition.timeUnit === 'WEEK') {
            let start = dateCondition.fixDate.split("-");
            dateCondition.fixDate = getDateOfWeek(start[1], start[0]);
            }
            if (dateCondition.timeUnit === 'QUARTER') {
            dateCondition.fixDate = showQuerterFormatter(dateCondition.fixDate)
            }
        }
        // 对比项的时间配置
        if (compareTimerConfig.fixDate && 
            compareTimerConfig.dateMode === 'FIXDATE') {
            if (compareTimerConfig.timeUnit === 'WEEK') {
            let fixDate = compareTimerConfig.fixDate.split("-");
            compareTimerConfig.fixDate = getDateOfWeek(fixDate[1], fixDate[0]);
            }
            if (compareTimerConfig.timeUnit === 'QUARTER') {
                compareTimerConfig.fixDate = showQuerterFormatter(compareTimerConfig.fixDate)
            }
        }

        curMetricsItem.value = cloneVal
        const indexCard = Object.keys(cards)?.find((item:any) => item === val.id)
        
        if (indexCard) {
            metricsLeftConfig.MetricsTreeCard[val.id] = Object.assign({},metricsConfigObj.value, cards[val.id])
        } else {
            const mergeData = Object.assign({},metricsConfigObj.value, cloneVal)
            metricsLeftConfig.MetricsTreeCard[val.id] = _.cloneDeep(mergeData)
        }
    })

    const previewApi = async (card: any) => {
        try {
            const res = await API.metricsTree.postCardPreview(card);
            return res
        } catch (error) {throw error;}
    };
    // 统计周期跟默认数据时间粒度保持一致
    const getFilterDimension = async (id: any) => {
        try {
            const { code, data } =
                await API.metricsModelRelation.getGetMetricsFilterById({
                    id
                });
                if (code === 200) {
                    return data
                }
        } catch (error) {}
    };
    // 定义预览接口的参数
    const getPreviewParams = async (v:any) => {
        const res = await getFilterDimension(v.metricsId);
        v.keys = v.id
        const {id, metricsName, metricsId, cardName, keys} = v 
        const val = {
            id,
            metricsName,
            metricsId,
            cardName,
            keys
        }
        const mergeData = Object.assign({},metricsConfigObj.value, val)
        if (res?.ifGroupBy) {
            mergeData.dateCondition.timeUnit = res?.timeframe?.toLocaleUpperCase()
        } else {
            mergeData.dateCondition.timeUnit = metricsConfigObj.value.metricsSetting.statisticalPeriod.timeUnit
        }
        mergeData.cardName = mergeData.metricsName
        delete mergeData.compare
        return mergeData
    }

    // 添加指标卡时补充cards的数据
    const getDataConfig = (val:any) => {
        curMetricsItem.value = val
        metricsLeftConfig.MetricsTreeCard[val.id] = _.cloneDeep(val)
        cards[val.id] = metricsLeftConfig.MetricsTreeCard[val.id]
        const manyCardIndex = Object.keys(cards).filter(item => !!item && item != 'undefined')
        manyCardList.value = manyCardIndex.map((item:any) => {
            return {
                ...cards[item]
            }
        })
    }
    // 第一次创建一个指标卡时
    const firstMetricsCard = async (v:any)=>{
        const previewParams = await getPreviewParams(v)
        previewApi(previewParams).then((res:any)=>{
            if (res.code === 200) {
                delete res.data?.sqlFormat
                isEditStatus.value = true
                const otherParams = {
                    type: 'indexCard', // 跟符号节点做区分
                    children: [],
                    heightLightLine: true, // 创建时默认选中高亮
                    rootTreeCard: true,  // 主卡蓝条高亮
                    parentId: '0000', // 根节点卡片父id
                }
                const newNodePramas = Object.assign(metricsConfigObj.value, res.data)
                const getPreviewData = {
                    ...newNodePramas,
                    compare: res.data?.compare || metricsConfigObj.value.compare,
                    id: res.data.keys
                }

                const mergeData = _.cloneDeep(getPreviewData)
                getDataConfig(mergeData)
                firstMetricsData.value = _.cloneDeep({...getPreviewData,...otherParams})
            } else {
                Message.error(res.msg)
            }
        })
    }
    // 添加指标卡时
    Bus.on('addMetricsCard', (v:any) => {
        getDataConfig(v)
    })

    // 预览结果成功状态了可以替换指标
    const exchangeMetricsCard = (targetCardData:any, sourceCardData:any) => {
        const sourceIndex = manyCardList.value.findIndex((items:any) => items.id === sourceCardData.id)
        manyCardList.value.splice(sourceIndex, 1, targetCardData)
        cards = {}
        metricsLeftConfig.MetricsTreeCard = {}
        curMetricsItem.value = targetCardData
        manyCardList.value.forEach((item:any) => {
            cards[item.id] = item
            metricsLeftConfig.MetricsTreeCard[item.id] = item
        })
    }
    // 替换指标时
    Bus.on('replaceSuccessMertrics', (targetNode:any, sourceNode:any) => {
        exchangeMetricsCard(targetNode, sourceNode)
    })

    // 指标树编辑状态时的数据
    Bus.on('getEditMetricTreeData', (cardData:any, graphTree:any, id:any) => {
        treeEditId.value = id
        if (cardData) {
            metricsLeftConfig.MetricsTreeCard = {}
            manyCardList.value = cardData
            curMetricsItem.value = graphTree
            cardData.forEach((item:any) => {
                item.id = item.keys
                metricsLeftConfig.MetricsTreeCard[item.keys] = item
                cards[item.keys] = item
            })
            isEditStatus.value = true
            timer.value = new Date().getTime()
            metricsLeftConfig.MetricsTreeCard[curMetricsItem.value.id]._timer=timer.value 

        }
    })
    // 预览结果
    const reviewResultData = async (v:any) => {    
        const previewParams = _.cloneDeep(v)
        if (!previewParams?.compare?.compareName) {
            delete previewParams.compare
        }
        delete previewParams.dateTime
        previewApi(previewParams).then((res:any)=>{
            if (res.code === 200) {
                // 预览成功了就要将当前选中指标数据给替换掉最新状态哟
                delete res.data?.sqlFormat
                const previewCardResult = Object.assign({},v, res.data)
                const sourceIndex = manyCardList.value.findIndex((items:any) => items.id === v.id)
                manyCardList.value.splice(sourceIndex, 1, previewCardResult)
                cards = {}
                manyCardList.value.forEach((item:any) => {
                    cards[item.id] = item
                })
                // 这时你就要把数据到给脑图那里作为graph收集哟
                Bus.emit('previewMetricsCard', {
                    ...previewCardResult,
                    compare: v?.compare || defaultConfig.compare,
                    id: v.keys,
                })
                Message.success('预览成功')
            } else {
                Message.error(res.msg)
            }
        })
    }
    // 指标树保存
    const handleIndexSave = () => {
        if (manyCardList.value) {
            Bus.emit('metricsCardSave',manyCardList.value, metricsName.value, addDesciptValue.value, treeEditId.value)
        } else {
            Message.warning('至少要选择一个指标')
            metricsName.value = '指标树名称';
            addDesciptValue.value = ''
        }
    }
    // tree打平
    const treeToList = (data:any) => {
        let res : any= []
        for (const item of data) {
            const { children, ...i } = item
            if (children && children.length) {
                res = res.concat(treeToList(children))
            } 
            
            res.push(i)
        }
        return res
    }

    // 删除指标卡
    const onRemoveMainCard = (isMainCard:boolean, sourceCardData?:any, deleteAfterData?:any) => {
        if (isMainCard) { 
            isEditStatus.value = false
            metricsLeftConfig.MetricsTreeCard = {}
            initCardParam.value = null
            manyCardList.value = null 
            addDesciptValue.value = '' // 清空描述咯
            metricsName.value = '指标树名称';
            store.commit('indextree/getMetricsDescript', '');
            cards = {}
        } else {
            const deleteCards = treeToList([deleteAfterData])
            const metricsCards = deleteCards?.filter((item:any) => item.type === 'indexCard')
            
            const isHasCurrentNode = metricsCards?.find((item:any) => item.id === curMetricsItem.value.id)
            manyCardList.value = metricsCards
            cards = {}
            manyCardList.value.forEach((item:any)=>{
                cards[item.id] = item
            })
            // 如果删除的指标正好是当前选中的呢
            if (!isHasCurrentNode) {
                metricsLeftConfig.MetricsTreeCard = {} // 传递给右侧配置的数据为空
            }
        }
        
    }
    
    onMounted(() => {
        getClassfiyList()
        if (!id.value) {
            metricsName.value = '指标树名称'
            addDesciptValue.value = ''
        } else {
            metricsName.value = historyName.value
            addDesciptValue.value = metricsDescript.value
        }
    })

</script>

<template>
<section>
    <header class="metrics-created-graph">
        <index-tree-header>
            <template #left>
                <a-typography-paragraph
                    editable
                    v-model:editText="metricsName"
                >
                    <span class="buildIndexName">{{metricsName}}</span>
                </a-typography-paragraph>
            </template>
            <template #right>
                <a-popover position="bottom" 
                    content-class="popContent"
                    arrow-class="arrowClass"
                    width="330px"
                    :popup-visible="popupVisible">
                    <a-button type="text" @click="()=>popupVisible = true">添加描述</a-button>
                    <template #content>
                        <span class="modal-title fw">添加描述</span>
                        <div class="text-style">
                            <a-textarea v-model="addDesciptValue" :style="{width: '339px', height: '90px'}" placeholder="请输入" :max-length="200" allow-clear show-word-limit />
                        </div>
                        <div class="bottom-btn">
                            <a-button size="mini" @click="()=>{
                                popupVisible=false
                            }">取消</a-button>
                        
                            <a-button class="ml-6" size="mini" type="primary"  @click="()=>popupVisible=false">确认</a-button>
                        </div>
                    </template>
                </a-popover>
                <a-button class="ml-10" @click="() => {
                    router.push({
                        name: RouteNames.ROUTER_INDEXTREE
                    })
                }">取消</a-button>
            
                <a-button class="ml-10" type="primary" @click="handleIndexSave">保存</a-button>
            </template>
        </index-tree-header>
    </header>
    <main>
       <div class="index-wrapper" :style="{marginTop:isNotMicroApp?'60px':'0'}">
        <graph-content 
            ref="graphContent" 
            class="index-wrapper_left" 
            :setCardData="setCardData"
            @firstMetricsCard="firstMetricsCard"
            @removeMainCard="onRemoveMainCard"
            :showMainGraph = 'isEditStatus'
            :firstMetricsData="firstMetricsData"

        ></graph-content>
        <div v-if="!isEditStatus" class="noconfig">
            <span>请先点击选择一个指标再来配置</span>
        </div>
        <index-config
            v-else 
            ref="addMetricsCardRef"
            class="index-wrapper_right"
            :metrics-config="metricsLeftConfig.MetricsTreeCard[curMetricsItem.id]"
            @reviewResultData = "reviewResultData"
            :initCardParam="initCardParam"
            :key="timer"
        ></index-config>
    </div> 
    </main>
</section>
</template>

<style lang="scss" scoped>
    .arco-typography-edit-content {
        margin-left: 0;
    }
    .buildIndexName {
        font-size: 20px;
        font-weight: bold;
    }
    .index-wrapper {
        display: flex;
        // margin-top: 60px;
        height: calc(100vh - 3.75rem);
        background: #EFF1F7;
        &_left {
            padding: 18px;
           width: calc(100% - 354px);
        }
        &_right {
            width: 318px;
        }
        .noconfig {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #fff;
            width: 318px;
        }
    }
    .metrics-created-graph {
        height: 3.75rem;
        width: 100%;
        z-index: 100;
        position: fixed;
        left: 0;
        top: 0;
    }
</style>